Property Value Shorthand
Objects in modern JavaScript have a nifty little trick up their sleeve. It's a small thing, but if you're not aware of it, it can cause a lot of confusion.
Suppose we have the following code:
const name = 'Ahmed';const age = 26;
const user = { name: name, age: age,};
console.log(user);// { name: 'Ahmed', age: 26 }
We're creating a user
object with two properties, name
and age
. We're assigning those properties to variables of the same name.
It does feel a bit redundant, though, doesn't it? We're assigning name
to name
, and assigning age
to age
.
Modern JavaScript gives us a convenient shorthand we can use in this situation:
const name = 'Ahmed';const age = 26;
const user = { name, age,};
console.log(user);// { name: 'Ahmed', age: 26 }
This is known as the property value shorthand. When creating an object, we can omit the values if they share the same name as the property.
The end result is the same, but it's a bit more terse.